//
//  AppTools.m
//  ChengHuiTong
//
//  Created by ypwl on 15/11/6.
//  Copyright © 2015年 张文权. All rights reserved.
//

#import "AppTools.h"

//推荐缓存目录
#define RecommendPath @"Recommend"

void YPGoWebView(NSString *urlStr,UINavigationController *nav){
    
    RxWebViewController *webView = [[RxWebViewController alloc]initWithUrl:urlStr];
    [nav pushViewController:webView animated:YES];
};

//获取还款方式
NSString * YPGetRepayments(NSString *style){
    NSString *repayment;
    
    if ([style intValue]== 0) {
        
        repayment = @"等额本息";
        
    }else if ([style intValue]== 3){
        
        repayment= @"先息后本";
        
    }else if ([style intValue]== 4){
        
        repayment= @"等额本金";
        
    }else if ([style intValue]== 5){
        
        repayment= @"到期一次还本付息";
        
    }else{
        
        repayment= @"其他";
    }
    
    return repayment;
}

@implementation AppTools{
    
    
}

+ (UIImage*)imageWithSize:(CGSize)size borderColor:(UIColor *)color borderWidth:(CGFloat)borderWidth
{
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [[UIColor clearColor] set];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    CGContextSetLineWidth(context, borderWidth);
    CGContextSetStrokeColorWithColor(context, color.CGColor);
    CGFloat lengths[] = { 3, 1 };
    CGContextSetLineDash(context, 0, lengths, 1);
    CGContextMoveToPoint(context, 0.0, 0.0);
    CGContextAddLineToPoint(context, size.width, 0.0);
    CGContextAddLineToPoint(context, size.width, size.height);
    CGContextAddLineToPoint(context, 0, size.height);
    CGContextAddLineToPoint(context, 0.0, 0.0);
    CGContextStrokePath(context);
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
+ (void)setListInfo:(NSDictionary *)array type:(CacheType)type
{
    
    [self deleteListInfoWithType:type];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath;
    switch (type) {
        case Recommend:
            filePath = [path stringByAppendingPathComponent:RecommendPath];
            break;
        default:
            break;
    }
    
    NSLog(@"%@",filePath);
    [array writeToFile:filePath atomically:NO];
    
    
}

+ (NSDictionary *)getListInfoWithType:(CacheType)type{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath;
    switch (type) {
        case Recommend:
            filePath = [path stringByAppendingPathComponent:RecommendPath];
            break;
        default:
            break;
    }
    
    //  NSLog(@"%@",filePath);
    
    NSDictionary*dic=[NSDictionary dictionaryWithContentsOfFile:filePath];
    
    return dic;
}


+ (void)deleteListInfoWithType:(int)type{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    NSString *filePath;
    
    
    switch (type) {
        case Recommend:{
            
            filePath=RecommendPath;
        }
            break;
            
        default:
            break;
    }
    
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filePath] error:NULL];
}

+(UIColor *) colorWithHexString: (NSString *) stringToConvert  //@"#5a5a5a"
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    
    if ([cString length] < 6) return [UIColor blackColor];
    
    // strip 0X if it appears
    
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    
    NSRange range;
    
    range.location = 0;
    
    range.length = 2;
    
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
            
                           green:((float) g / 255.0f)
            
                            blue:((float) b / 255.0f)
            
                           alpha:1.0f];
    
}


/**
 图片在前文字在后
 
 @param image 图片
 @param content 文字内容
 @return 返回文字在前图片在后的富文本
 */
+ (NSMutableAttributedString *)getAttributedStringWithImage:(UIImage *)image string:(NSString *)content{
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
    
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image = image;
    attach.bounds = CGRectMake(0, -1, image.size.width, image.size.height);
    
    NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    [string appendAttributedString:str];
    
    [string appendAttributedString:textStr];
    
    return string;
}


/**
 返回利率跟加息拼接的属性字符串
 
 @param rate 年利率
 @param rateAdd 加息利率
 @param fontSize 字体大小
 @return 属性字符串
 */
+ (NSMutableAttributedString*)getAttributedStringWithRate:(NSString *)rate
                                                  rateAdd:(NSString *)rateAdd
                                                 fontSize:(CGFloat)fontSize{
    
    NSString*oldApr=rate.floatValue > rate.integerValue ? rate : [NSString stringWithFormat:@"%ld",(long)rate.integerValue];
    
    NSString*addApr=rateAdd;
    
    UIFont *font=[UIFont systemFontOfSize:fontSize];
    
    if (addApr && [addApr floatValue]>0) {
        
        //NSString*newApr=[NSString stringWithFormat:@"%.1f",[oldApr floatValue]-[addApr floatValue]];
        
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        
        formatter.numberStyle = NSNumberFormatterRoundFloor;
        
        NSString*newApr = [formatter stringFromNumber:[NSNumber numberWithFloat:[oldApr floatValue]-[addApr floatValue]]];
        
        NSMutableAttributedString*str=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%%+%@%%",newApr,addApr]];
        
        [str addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, newApr.length)];
        
        return str;
        
        
    }else{
        
        NSMutableAttributedString*str=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%%",oldApr]];
        
        [str addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, oldApr.length)];
        
        return str;
        
    }
    
    
}

//字符串转货币格式
+ (NSString*)numberToDecimal:(NSString*)numberstring{
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    
    //    enum {
    //        NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
    //        NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
    //        NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
    //        NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
    //        NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
    //        NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
    //    };
    //    typedef NSUInteger NSNumberFormatterStyle;
    //    各个枚举对应输出数字格式的效果如下：
    //    [1243:403] Formatted number string:123456789
    //    [1243:403] Formatted number string:123,456,789
    //    [1243:403] Formatted number string:￥123,456,789.00
    //    [1243:403] Formatted number string:-539,222,988%
    //    [1243:403] Formatted number string:1.23456789E8
    //    [1243:403] Formatted number string:一亿二千三百四十五万六千七百八十九
    
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    
    NSString *string = [formatter stringFromNumber:[NSNumber numberWithDouble:[numberstring doubleValue]]];
    
    if ([string intValue] == 0) {
        
        string = @"0.00";
    }
    
    return string;
    
}

//删除中间的，%
+(NSString *)stringDeleteString:(NSString *)str;
{
    NSMutableString *str1 = [NSMutableString stringWithString:str];
    for (int i = 0; i < str1.length; i++) {
        unichar c = [str1 characterAtIndex:i];
        NSRange range = NSMakeRange(i, 1);
        if ( c == ',' || c == '%') { //此处可以是任何字符
            [str1 deleteCharactersInRange:range];
            --i;
        }
    }
    NSString *newstr = [NSString stringWithString:str1];
    return newstr;
}

//处理null数据
+ (NSString *)handleNullToString:(NSString *)str{
    
    if (str == nil) {
        return @"";
    }
    if (str == NULL) {
        return @"";
    }
    if ([str isKindOfClass:[NSNull class]]) {
        return @"";
    }
    if (![str isKindOfClass:[NSString class]]){
        return [NSString stringWithFormat:@"%@",str];
    }
    if ([str isEqualToString:@"<null>"]) {
        return @"";
    }
    if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        return @"";
    }
    
    return str;
}


/**
 根据输入的金额计算总收益
 
 @param enterAmount 输入的金额
 @param apr         年利率
 @param timeLimit   期限
 @param style       还款方式 0：等额本息 3：先息后本 4：等额本金 5：到期一次还本付息
 @param is_datetype 0按月计算  1按天计算
 
 @return 总收益
 */
+ (NSString *)getFinalProfitWithEnterAmount:(double)enterAmount
                                        apr:(NSString *)apr
                                  timeLimit:(NSString *)timeLimit
                                      style:(NSString *)style
                                is_datetype:(NSString *)is_datetype
{
    
    if (enterAmount == 0) {
        return @"0.00";
    }
    
    NSString *finalProfit = @"";
    
    //        年利率
    double yearApr = [apr doubleValue]/100;
    //   月利率
    double monthlyInteres = yearApr/12.00000000;
    //   月利率（四舍五入转成8位浮点数）
    double roundmonthlyInteres =[[self notRounding:monthlyInteres afterPoint:8] doubleValue];
    
    NSLog(@"月利率=%.8f",roundmonthlyInteres);
    //            投资几个月 时间
    int time_limit = [timeLimit intValue];
    
    //0：等额本息
    if ([style intValue]==0){
        //        按月计算
        if ([is_datetype intValue]==0) {
            
            double expectedEarnings = 0.0 ;
            
            //                每期还款本息
            // powl(n, m) n的m次方，long double类型
            double  reimbursementInterest = enterAmount * roundmonthlyInteres * powl((1+roundmonthlyInteres), time_limit)/(powl((1+roundmonthlyInteres), time_limit)-1);
            
            NSLog(@"每期还款本息%.8f",reimbursementInterest);
            
            //             四舍五入之后的每期还款本息
            double roundReimbursementInterest = [[self notRounding:reimbursementInterest afterPoint:2] doubleValue];
            
            
            for (int i = 1; i < time_limit+1; i++){
                
                double everyMouthReimbursementInterest =((enterAmount * roundmonthlyInteres)-roundReimbursementInterest)*(pow((1+roundmonthlyInteres), i-1)) +roundReimbursementInterest;
                
                double roundeEveryMouthReimbursementInterest = [[self notRounding:everyMouthReimbursementInterest afterPoint:2] floatValue];
                
                expectedEarnings += roundeEveryMouthReimbursementInterest;
                
                
            }
            
            
            finalProfit = [NSString stringWithFormat:@"%.2f",expectedEarnings];
            
            
        }
        
        
        
    }
    //3：先息后本
    else if ([style intValue]==3){
        
        //        按月计算  还有按天计算的  暂时没加此功能
        if ([is_datetype intValue]==0) {
            
            //格式化对象（NSRoundPlain：四舍五入；2：保留小数点后两位）
            NSDecimalNumberHandler*roundUp = [NSDecimalNumberHandler
                                              decimalNumberHandlerWithRoundingMode:NSRoundPlain
                                              scale:2
                                              raiseOnExactness:NO
                                              raiseOnOverflow:NO
                                              raiseOnUnderflow:NO
                                              raiseOnDivideByZero:YES];
            
            
            
            //创建一个月利率的十进制对象
            NSDecimalNumber * dnMonthlyInteres = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",monthlyInteres]];
            NSLog(@"monthlyInteres=%@",dnMonthlyInteres);
            
            
            //创建一个期限的十进制对象
            NSDecimalNumber * time_limit1 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%d",time_limit]];
            
            
            
            //创建一个金额的十进制对象
            NSDecimalNumber * enterAmount1 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",enterAmount]];
            NSLog(@"金额=%@",[enterAmount1 decimalNumberByMultiplyingBy:dnMonthlyInteres]);
            NSLog(@"金额x利率===%@",[enterAmount1 decimalNumberByMultiplyingBy:dnMonthlyInteres withBehavior:roundUp]);
            
            //金额
            NSLog(@"金额x利率x期限=%@", [[enterAmount1 decimalNumberByMultiplyingBy:dnMonthlyInteres withBehavior:roundUp]decimalNumberByMultiplyingBy:time_limit1]);
            
            ////                        利息
            
            finalProfit =  [NSString stringWithFormat:@"%.2f",[[NSString stringWithFormat:@"%@",[[enterAmount1 decimalNumberByMultiplyingBy:dnMonthlyInteres withBehavior:roundUp]decimalNumberByMultiplyingBy:time_limit1]] doubleValue]];
            
            
        }
        
        
        
    }
    //4：等额本金
    else if ([style intValue]==4){
        //        按月计算
        if ([is_datetype intValue]==0) {
            /*
            等额本金还款方式的利息收益计算：
            
            每月应还本金=总本金/还款月数  #精确到小数点后2位
            每月应还利息=（本金-累计已还本金）×月利率   #精确到小时候2位
            
            总利息，即为所有月份利息相加之和。
             */
            
            //格式化对象（NSRoundPlain：四舍五入；2：保留小数点后两位）
            NSDecimalNumberHandler*roundUp = [NSDecimalNumberHandler
                                              decimalNumberHandlerWithRoundingMode:NSRoundPlain
                                              scale:2.0f
                                              raiseOnExactness:NO
                                              raiseOnOverflow:NO
                                              raiseOnUnderflow:NO
                                              raiseOnDivideByZero:YES];
            
            
            //创建总本金十进制对象
            NSDecimalNumber *principalDN = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",enterAmount]];
            
            //创建一个期限的十进制对象
            NSDecimalNumber * time_limitDN = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%d",time_limit]];
            
            //创建一个月利率十进制对象
            NSDecimalNumber *rateMonthlyDN = [self banker:monthlyInteres afterPoint:8];
            
            //每月应还本金十进制对象(总本金/还款月数)
            NSDecimalNumber *principalMonthlyDN = [principalDN decimalNumberByDividingBy:time_limitDN withBehavior:roundUp];
            
            
            NSLog(@"本金:%@",principalDN);
            NSLog(@"每月应还本金:%@",principalMonthlyDN);
            NSLog(@"月利率:%@",rateMonthlyDN);
            
            
            //初始化总利息十进制对象
            NSDecimalNumber *finalProfitDN = [NSDecimalNumber decimalNumberWithString:@"0"];
            
            for (int i = 1; i < time_limit + 1; i ++) {
                
                //当前月份-1的十进制
                NSDecimalNumber *monthDN = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%d",i-1]];
                
                //累计已还本金的十进制对象（每月本金*（当前月份-1））
                NSDecimalNumber *cumulativePrincipalDN = [principalMonthlyDN decimalNumberByMultiplyingBy:monthDN withBehavior:roundUp];
                
                //剩余本金（总本金-累计已还本金）
                NSDecimalNumber *surplusPrincipalDN = [principalDN decimalNumberBySubtracting:cumulativePrincipalDN withBehavior:roundUp];
                
                //每月应还利息 = 剩余本金×月利率
                NSDecimalNumber *interestMonthlyDN = [surplusPrincipalDN decimalNumberByMultiplyingBy:rateMonthlyDN withBehavior:roundUp];
                
                //总利息
                finalProfitDN = [finalProfitDN decimalNumberByAdding:interestMonthlyDN withBehavior:roundUp];
                
                NSLog(@"\n累计本金:%@\n剩余本金:%@\n每月还息:%@\n总息:%@",cumulativePrincipalDN,surplusPrincipalDN,interestMonthlyDN,finalProfitDN);
            }
            
            finalProfit = [NSString stringWithFormat:@"%.2f",[finalProfitDN doubleValue]];
            
        }
        
            
    }
    //5：到期一次还本付息
    else if ([style integerValue] == 5){
        //        按月计算
        if ([is_datetype intValue]==0) {

            //利息
            double  reimbursementInterest = enterAmount * roundmonthlyInteres * time_limit;
            
            NSLog(@"一次性还本利息息%.8f",reimbursementInterest);
            
            //四舍五入之后的利息
            double roundReimbursementInterest = [[self notRounding:reimbursementInterest afterPoint:2] doubleValue];

            finalProfit = [NSString stringWithFormat:@"%.2f",roundReimbursementInterest];
            
        }
    }

    
    return finalProfit;
}

+ (NSString *)notRounding:(double)price afterPoint:(int)position{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    
    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
    //四舍五入运算
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    return [NSString stringWithFormat:@"%@",roundedOunces];
}

+ (NSDecimalNumber *)banker:(double)price afterPoint:(int)position{
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    
    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
    //四舍五入运算
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    return  roundedOunces;
}

/**
 创建表尾通用label
 
 @return label
 */
+ (UILabel *)getFootLabel{
    
    //表尾
    UILabel *footLabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, 30)];
    footLabel.textColor =  UIColorFromString(@"#969696");
    footLabel.font =[UIFont systemFontOfSize:11];
    footLabel.textAlignment =NSTextAlignmentCenter;
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@"账户资金由徽商银行存管"];
//    attch.image = [UIImage imageNamed:@"dsfzjtg"];
    attch.image = ImageNamed(@"hsbank");
    attch.bounds = CGRectMake(-2, -2, 12, 12);
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    [attri insertAttributedString:string atIndex:0];
    footLabel.attributedText = attri;
    return footLabel;
}


/**
 图片+文字
 
 @param image 图片
 @param content 文字内容
 @param imageLeft 图片在左或者右
 @return 返回文字在前图片在后的富文本
 */
+ (NSMutableAttributedString *)getAttributedStringWithImage:(UIImage *)image
                                                     string:(NSString *)content
                                                  imageLeft:(BOOL)imageLeft{
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
    
    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image = image;
    attach.bounds = CGRectMake(0, -1, image.size.width, image.size.height);
    
    NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    if (imageLeft) {
        [string appendAttributedString:str];
        
        [string appendAttributedString:textStr];
    }else{
        
        [string appendAttributedString:textStr];
        
        [string appendAttributedString:str];
    }
    
    
    return string;
}

//获取当前的viewcontroller
+ (UIViewController *)getCurrentVC{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    
    if (window.windowLevel != UIWindowLevelNormal){
        
        NSArray *windows = [[UIApplication sharedApplication] windows];
        
        for(UIWindow * tmpWin in windows){
            if (tmpWin.windowLevel == UIWindowLevelNormal){
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        
        result = nextResponder;
    
    else
        
        result = window.rootViewController;
    
    return result;
    
}

//判断是否为整形
+ (BOOL)isPureInt:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

//判断是否为浮点形
+ (BOOL)isPureFloat:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
   
}

@end
